import React, {Component} from 'react';
import NavHeader from '../../../components/NavHeader/NavHeader'
import './Main.scss';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import changeTab from '../actions/changeTabAction'
import { Route, NavLink, Switch } from 'react-router-dom'
import Menu from '../Menu/Menu';
import Comment from '../Comment/Comment';
import Restanurant from '../Restanurant/Restanurant';
class Main extends Component {
    constructor(props) {
        super(props);
        this.state = {};
        this.resetActiveKey();
    }

    // 重置active-key
    resetActiveKey () {
        let url = window.location.href;
        let index = url.indexOf('#');
        let _router = url.slice(index + 1);
        if(_router === '/') {
            _router = '/menu';
        }
        let key = _router.slice(1);
        this.props.changeTabAction({
            activeKey: key
        })
    }

    // 改变 active-tab
    changeTab(key) {
        this.props.changeTabAction({
            activeKey: key
        })
    }

    // 渲染tab
    renderTabs () {
        let tabs = this.props.tabs;
        let activeKey = this.props.activeKey;
        return tabs.map((item) => {
            let cls = activeKey === item.key ? 'tab-item active' : 'tab-item';
            return <NavLink
                activeClassName="active"
                to={'/' + item.key}
                className={cls}
                key={item.key}
                onClick={() => this.changeTab(item.key)}
            >{item.name}</NavLink>
        })
    }


    render() {
        return (
          <div className="details-wrapper">
              <NavHeader title="商家"></NavHeader>
              <div className="tab-bar">
                  {this.renderTabs()}
              </div>
              <Switch>
                  <Route exact path="/" component={Menu}/>
                  <Route  path="/menu" component={Menu}/>
                  <Route path="/comment" component={Comment}/>
                  <Route path="/restanurant" component={Restanurant}/>
              </Switch>
          </div>
        )
    }
}


export default connect(
    (state) => {
        return {
           tabs: state.changeTabReducer.tabs,
            activeKey: state.changeTabReducer.activeKey
        }
    },
    (dispatch) => {
        return {
            changeTabAction: bindActionCreators(changeTab, dispatch)
        }
    }
)(Main);
